<?php

class Media
{
	private $_media;
	private $_id;
	private $_db;
	private $_result;
	
	public function __construct($media, $id)
	{
		$this->_db = new PDO('mysql:host=localhost;port=3306;dbname=mediadevil','root','c3589');
	    $this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	    
		$this->setMedia($media);
		$this->setId($id);
		$this->setResult();
	}
	
	private function setMedia($media)
	{
		$this->_media = strtolower($media);
	}
	
	private function setId($id)
	{
		$this->_id = $id;
	}
	
	public function setResult()
	{
		$sql = 'SELECT * FROM media_'.$this->getMedia().' WHERE '.$this->getMedia().'_id = '.$this->getId();
		
    	if(!$query = $this->_db->query($sql))
    	{
    		//log error!
    		return false;    	
    	}
    	else 
    	{
    		while($result = $query->fetch(PDO::FETCH_ASSOC))
	    	{
	    		$this->_result = $result;
	    		
	    		foreach ($result as $key=>$value)
	    		{
	    			$key = strstr($key, '_');
	    			$this->$key = $result[$this->_media . $key];
	    		}
	    	}
	    	return true;
    	}
	}
	
	private function getId()
	{
		return $this->_id;
	}
	
	public function getArray()
	{
		return $this->_result;
	}
	
	private function getMedia()
	{
		return $this->_media;
	}
	
	public function toString($tableHeaders, $hiddenFields)
	{
		if(isset($hiddenFields) && (!empty($hiddenFields)))
		{
			foreach ($hiddenFields as $hiddenField)
			{
				foreach ($this->_result as $key=>$item)
				{
					if($key == $hiddenField)
					{
						unset($this->_result[$key]);
					}
				}
			}
		}
		
		$return = '<table border="1"><tr>';
		
		foreach ($tableHeaders as $tableHeader)
		{
			$return .= '<th>'.$tableHeader.':</th>';
		}
		
		$return .= '</tr><tr>';		
		
		foreach ($this->_result as $key=>$item)
		{
			$return .= '<td>'.$this->_result[$key].'</td>';
		}
		
		$return .= '</tr></table>';		
		return $return;
	}
}